package com.akino.gulimall.cart.service.Impl;

import com.akino.common.utils.R;
import com.akino.gulimall.cart.feign.ProductFeignService;
import com.akino.gulimall.cart.interceptor.CartInterceptor;
import com.akino.gulimall.cart.service.CartService;
import com.akino.gulimall.cart.vo.Cart;
import com.akino.gulimall.cart.vo.CartItem;
import com.akino.gulimall.cart.vo.SkuInfoVo;
import com.akino.gulimall.cart.vo.UserInfoTo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author Akino
 * @version 1.0
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    ThreadPoolExecutor executor;

    private final String CART_PREFIX = "gulimall:cart:";  // 前缀

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        String string = (String) ops.get(skuId.toString());
        if (!StringUtils.isEmpty(string)){
            // redis中已有此商品
            CartItem hasCartItem = JSON.parseObject(string, CartItem.class);
            hasCartItem.setCount(num);
            ops.put(skuId.toString(),JSON.toJSONString(hasCartItem));
            return hasCartItem;
        }
        // 将新商品添加到购物车
        CartItem cartItem = new CartItem();
        CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
            // 远程查询要添加的商品的信息
            R skuInfo = productFeignService.info(skuId);
            SkuInfoVo info = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
            });
            cartItem.setSkuId(skuId);
            cartItem.setTitle(info.getSkuTitle());
            cartItem.setImage(info.getSkuDefaultImg());
            cartItem.setPrice(info.getPrice());
            cartItem.setCount(num);
        },executor);
        // 获取商品套餐
        CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
            List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
            cartItem.setSkuAttr(skuSaleAttrValues);
        }, executor);
        CompletableFuture.allOf(getSkuInfoTask,getSkuSaleAttrValues).get();
        String s = JSON.toJSONString(cartItem);
        ops.put(skuId.toString(),s);
        return cartItem;
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> ops = getCartOps();
        String s = (String) ops.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(s, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        // 判断用户是否登陆
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            // 用户已登陆，使用用户的id
            // 如果用户在未登录时添加了购物车，在登陆之后合并用户已有的购物车
            String carKey = CART_PREFIX + userInfoTo.getUserId();
            String tempCarKey = CART_PREFIX + userInfoTo.getUserKey();
            // 判断临时购物车里有无数据
            List<CartItem> tempCartItems = getCartItems(tempCarKey);
            if (tempCartItems!=null){
                // 购物车合并
                for (CartItem item : tempCartItems) {
                    addToCart(item.getSkuId(), item.getCount());
                }
                // 合并完成，清空临时购物车
                clearCart(tempCarKey);
            }
            // 获取整个购物车数据
            List<CartItem> cartItems = getCartItems(carKey);
            cart.setItems(cartItems);
        } else {
            // 用户未登录，使用临时用户的key
            String carKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> cartItems = getCartItems(carKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    /**
     * 同一线程下，获取到要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        // 获取当前用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (userInfoTo.getUserId()!=null){
            // 用户已登陆
            // gulimall:cart:1
            cartKey = CART_PREFIX+userInfoTo.getUserId();
        } else {
            // 用户未登陆
            cartKey = CART_PREFIX+userInfoTo.getUserKey();
        }
        // 对所有的cartKey绑定同一个Hash操作
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }
    /**
     * 获取临时用户的购物车
     */
    private List<CartItem> getCartItems(String carKey){
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(carKey);
        List<Object> values = hashOps.values();
        if (values!=null&&values.size()>0){
            List<CartItem> collect = values.stream().map(obj -> {
                String s = (String) obj;
                CartItem cartItem = JSON.parseObject(s, CartItem.class);
                return cartItem;
                }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    @Override
    public void clearCart(String cartKey){
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null){
            return null;
        }
        String cartKey = CART_PREFIX + userInfoTo.getUserId();
        List<CartItem> cartItems = getCartItems(cartKey);
        List<CartItem> collect = cartItems.stream()
                .filter(item -> item.getCheck())
                .map(item->{
                    // 商品更新为最新价格
                    R price = productFeignService.getPrice(item.getSkuId());
                    String data = (String) price.get("data");
                    item.setPrice(new BigDecimal(data));
                    return item;
                })
                .collect(Collectors.toList());
        return collect;
    }
}
